package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Content;
import com.jiawa.wiki.domain.Doc;
import com.jiawa.wiki.domain.DocExample;
import com.jiawa.wiki.exception.BusinessException;
import com.jiawa.wiki.exception.BusinessExceptionCode;
import com.jiawa.wiki.job.DocJob;
import com.jiawa.wiki.mapper.ContentMapper;
import com.jiawa.wiki.mapper.DocMapper;
import com.jiawa.wiki.mapper.DocMapperCustom;
import com.jiawa.wiki.req.DocQueryReq;
import com.jiawa.wiki.req.DocSaveReq;
import com.jiawa.wiki.response.DocResp;
import com.jiawa.wiki.response.PageResp;
import com.jiawa.wiki.utils.CopyUtil;
import com.jiawa.wiki.utils.RedisUtil;
import com.jiawa.wiki.utils.RequestContext;
import com.jiawa.wiki.utils.SnowFlake;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DocService {

    @Resource
    private DocMapper docMapper;

    @Resource
    private DocMapperCustom docMapperCustom;

    @Resource
    private ContentMapper contentMapper;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private DocJob docJob;

    @Resource
    private WsService wsService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    private final static Logger LOG = LoggerFactory.getLogger(DocService.class);

    /**
     * 支持分页查询：注意 PageHelper 只对一条查询sql有效，如果配置下有多个sql,应该写在要查询的sql上即可
     *
     * @param req
     * @return
     */
    public PageResp<DocResp> list(DocQueryReq req) {
        DocExample docExample = new DocExample();
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<Doc> docList = docMapper.selectByExample(docExample);

        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        LOG.info("总页数：{}", pageInfo.getPages());
        LOG.info("总行数：{}", pageInfo.getTotal());
        // 持久层的需要传化为 List<DocResp>
        /* List<DocResp> respList = new ArrayList<>();
         for (Doc doc : docList) {
            DocResp docResp = new DocResp();
            //BeanUtils.copyProperties(doc, docResp);
            // 单体复制
            DocResp copy = CopyUtil.copy(doc, DocResp.getClass());
            respList.add(copy);
        } */

        // 列表复制 上述代码简化
        List<DocResp> respList = CopyUtil.copyList(docList, DocResp.class);

        PageResp<DocResp> pageResp = new PageResp<>();
        pageResp.setList(respList);
        pageResp.setTotal(pageInfo.getTotal());
        LOG.info("{}", respList);
        return pageResp;
    }

    /**
     * 查询文档内容
     * 文档阅读数 +1
     *
     * @param id
     * @return
     */
    public String findContent(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        // 文档阅读数 +1
        docMapperCustom.increaseViewCount(id);
        if (ObjectUtils.isEmpty(content)) {
            return "";
        }
        return content.getContent();
    }

    /**
     * 查询所有文档
     *
     * @return
     */
    public List<DocResp> all(Long ebookId) {
        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(ebookId);
        docExample.setOrderByClause("sort asc");
        List<Doc> docList = docMapper.selectByExample(docExample);
        // 列表复制
        List<DocResp> respList = CopyUtil.copyList(docList, DocResp.class);
        LOG.info("{}", respList);
        return respList;
    }

    /**
     * 保存文档（看请求参数id是否为空） 修改文档
     * 操作了两个sql, 应该加入事务，要么两个同时成功 或 失败
     * @param req
     */
    @Transactional
    public void save(DocSaveReq req) {
        Doc doc = CopyUtil.copy(req, Doc.class);
        Content content = CopyUtil.copy(req, Content.class);
        if (ObjectUtils.isEmpty(doc.getId())) {
            // 新增 设置id 此ID是雪花算法实现 不是uuid 和自增ID
            doc.setId(snowFlake.nextId());
            doc.setViewCount(0); // 设置为 0，要不然是保存的是 null
            doc.setVoteCount(0);
            docMapper.insert(doc);

            // content 表 id 和 doc 一致
            content.setId(doc.getId());
            contentMapper.insert(content);
        } else {
            // 修改
            docMapper.updateByPrimaryKey(doc);

            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0) {
                contentMapper.insert(content);
            }
        }
    }

    /**
     * 根据ids删除
     *
     * @param ids
     */
    public void delete(List<Long> ids) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(ids);
        docMapper.deleteByExample(docExample);
    }

    /**
     * 点赞
     *  推送消息，使用异步解耦推送，如果websocket连接数比较多，前端迟迟收不到推送消息。
     * @param id
     */
    public void vote(Long id) {
        // docMapperCustom.increaseVoteCount(id);
        // 远程 ip + doc.id 作为 key, 24小时内不能重复，不能重复点赞
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + '_' + ip, 3600)) {
            docMapperCustom.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }

        // 推送点赞消息
        Doc docDb = docMapper.selectByPrimaryKey(id);
        String logId = MDC.get("LOG_ID");
        // 这里会开启一个异步线程
        //wsService.sendInfo("【" + docDb.getName() + "】被点赞", logId);
        // 方法二：不使用异步调用 使用roketmq
        rocketMQTemplate.convertAndSend("VOTE_TOPIC", "【" + docDb.getName() + "】被点赞");
    }

    /**
     * 定时更新电子书数据
     */
    public void updateEbookInfo() {
        docJob.updateEbookInfo();
    }
}
